var express = require('express');
var router = express.Router();
const shortid = require("shortid");
const AccountModel = require("../../models/AccountModel");
const moment = require("moment");
const mongoose = require('mongoose');

let checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware');

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

/* 记账本列表 */
router.get('/account', checkTokenMiddleware, async function(req, res, next) {
    console.log(req.user)
    try {
        const accounts = await AccountModel.find().sort({ time: -1 }).exec();
        return res.json({
            code: "0000",
            msg: "获取成功",
            data: accounts,
        });
    } catch (e) {
        console.error(e);
        return res.status(500).json({
            code: "1001",
            msg: "获取失败",
            data: {},
        });
    }
});

// 添加记录
router.get("/account/create", checkTokenMiddleware, (req, res, next) => {
    res.render("create");
});

// 新增记录
router.post("/account", checkTokenMiddleware, async (req, res, next) => {
    let id = shortid.generate();
    req.body.type = Number(req.body.type);
    req.body.time = moment(req.body.time).toDate();

    if (!req.body.type || !req.body.account || !req.body.remarks || !req.body.time || !req.body.title) {
        return res.status(400).json({
            code: "1003",
            msg: "参数不足",
            data: {},
        });
    }
    if (isNaN(req.body.account)) {
        return res.status(400).json({
            code: "1004",
            msg: "金额必须为数字",
            data: {},
        });
    }
    if (req.body.remarks.length > 30) {
        return res.status(400).json({
            code: "1005",
            msg: "备注最多30字",
            data: {},
        });
    }
    if (typeof req.body.type !== 'number' || (req.body.type !== 1 && req.body.type !== -1)) {
        return res.status(400).json({
            code: "1006",
            msg: "类型必须是 1 或 -1",
            data: {},
        });
    }

    try {
        const data = await AccountModel.create({ id, ...req.body });
        return res.json({
            code: "0000",
            msg: "添加成功",
            data: data,
        });
    } catch (err) {
        console.error(err);
        return res.status(500).json({
            code: "1002",
            msg: "添加失败",
            data: {}
        });
    }
});

// 删除记录
router.delete("/account/:id", checkTokenMiddleware, async (req, res) => {
    const id = req.params.id;
    try {
        const data = await AccountModel.deleteOne({ _id: id });
        if (data.deletedCount === 0) {
            return res.status(404).json({
                code: "1010",
                msg: "记录未找到",
                data: {},
            });
        }
        return res.json({
            code: "0000",
            msg: "删除成功",
            data: data,
        });
    } catch (err) {
        console.error(err);
        return res.status(500).json({
            code: "1010",
            msg: "删除失败",
            data: {},
        });
    }
});

// 获取单个账单信息
router.get("/account/:id", checkTokenMiddleware, async (req, res) => {
    const id = req.params.id;
    try {
        const data = await AccountModel.findById(id);
        if (!data) {
            return res.status(404).json({
                code: "1011",
                msg: "记录未找到",
                data: {},
            });
        }
        return res.json({
            code: "0000",
            msg: "获取成功",
            data: data,
        });
    } catch (err) {
        console.error(err);
        return res.status(500).json({
            code: "1011",
            msg: "获取失败",
            data: {},
        });
    }
});

// 更新单条账单信息
router.patch("/account/:id", checkTokenMiddleware, async (req, res) => {
    const id = req.params.id;
    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(400).json({
            code: "1013",
            msg: "无效的 ID",
            data: {}
        });
    }
    try {
        const result = await AccountModel.updateOne({ _id: id }, req.body);
        if (result.modifiedCount > 0) {
            const data = await AccountModel.findById(id);
            return res.status(200).json({
                code: "0000",
                msg: "更新成功",
                data: data
            });
        } else {
            return res.status(404).json({
                code: "1012",
                msg: "更新失败，记录未找到",
                data: {}
            });
        }
    } catch (error) {
        console.error(error);
        return res.status(500).json({
            code: "1014",
            msg: "服务器内部错误",
            data: {}
        });
    }
});

module.exports = router;
